package com.augmented.jellybean;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.graphics.Bitmap;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONObject;

import com.augmented.jellybean.util.DealParser;
import com.augmented.jellybean.util.ExpandableCustomAdapter;
import com.augmented.jellybean.util.ExpandableParent;
import com.augmented.jellybean.util.ImageParser;
import com.augmented.jellybean.util.JSONParser;
import com.augmented.jellybean.util.information;
import com.google.android.gms.maps.model.LatLng;


public class AugmentedJellybeanDealsScreenActivity extends Activity {

	private static final String DEALS_API_BASE = "https://webapi.blipadeal.com/api_get_category_deals_url?";
	private static final String STATUS = "SUCCESS";
	private static final String API_KEY_TOKEN = "E5027A7AF0B1B3EA21609DDC6346A000";
	private static final String API_SECRET_TOKEN = "51281574AD791DC951AC17510A4106A4";

	HashMap<Integer, ExpandableParent> dealMap = new HashMap<Integer, ExpandableParent>();

	Location myLocation;
	ExpandableParent theParent;

	private ExpandableListView mExpandableList;

	@SuppressWarnings("rawtypes")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.augmented_jellybean_deals_screen);

		mExpandableList = (ExpandableListView) findViewById(R.id.mainListView);

		// Getting LocationManager object from System Service LOCATION_SERVICE
		LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		//String provider = locationManager.getBestProvider(criteria, false);
		String provider = LocationManager.GPS_PROVIDER;
		Location location = locationManager.getLastKnownLocation(provider);
		myLocation = location;

		String fatWallet = "http://www.fatwallet.com/coupons/?filter=product";
		ArrayList<ArrayList> inputList = new ArrayList<ArrayList>();
		try {
			inputList = grabDeals(fatWallet);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		ArrayList<ExpandableParent> arrayParents = populateAdapter(inputList);

		// Set the ArrayAdapter as the ExpandableListView's adapter

		mExpandableList.setAdapter(new ExpandableCustomAdapter(AugmentedJellybeanDealsScreenActivity.this, arrayParents));
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private ArrayList<ExpandableParent> populateAdapter(ArrayList<ArrayList> inputList) {
		ArrayList<ExpandableParent> parentList = new ArrayList<ExpandableParent>();

		// Get the input lists from the inputList
		ArrayList<String> offerList = inputList.get(0);
		ArrayList<String> imgUrlList = inputList.get(1);
		ArrayList<String> cellList = inputList.get(2);

		int o = offerList.size(); int m = imgUrlList.size(); int c = cellList.size(); int finalSize = 0;

		if(o > m && o > c) {
			// o has the largest size
			if (m > c) 
				finalSize = c;
			else
				finalSize = m;
		} else if (o < m && o < c) {
			// o has the smallest size
			finalSize = o;
		} else if (o > m && o < c) {
			// m < o < c
			finalSize = m;
		} else if (o < m && o > c) {
			// c < o < m
			finalSize = c;
		} else {
			// Everything is the same size
			finalSize = o;
		}

		for (int i = 0; i < finalSize; i ++) {
			String offerTitle = offerList.get(i);
			String imageUrl = imgUrlList.get(i);
			ExpandableParent mParent = new ExpandableParent();

			mParent.setTitle(offerTitle);

			AsyncTask<String, Void, Bitmap> mySyncTask = new ImageParser().execute(imageUrl);
			Bitmap bmp = null;
			try {
				bmp = mySyncTask.get();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			mParent.setImg(bmp);
			dealMap.put(i, mParent);
			parentList.add(mParent);
		}
		return parentList;
	}

	@SuppressWarnings("rawtypes")
	public ArrayList<ArrayList> grabDeals(String url) throws IOException {

		ArrayList<ArrayList> returnList = new ArrayList<ArrayList>();

		ArrayList<String> imgUrls = new ArrayList<String>();
		ArrayList<String> offerTitles = new ArrayList<String>();
		ArrayList<String> offerPrices = new ArrayList<String>();
		ArrayList<String> offerOldPrices = new ArrayList<String>();
		ArrayList<String> offerCellList = new ArrayList<String>();


		int offerListSize = 0;

		AsyncTask<String, Void, Document> mySyncTask = new DealParser().execute(url);
		Document doc = null;
		try {
			doc = mySyncTask.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Elements offers = doc.getElementsByClass("offer-details-url");
		Elements offerCells = doc.getElementsByClass("offer-cell");
		Elements offerImages = doc.getElementsByAttribute("data-original");
		Elements offerPrice = doc.getElementsByClass("offer-price");

		if (offerImages != null && offers != null) {
			if (offerImages.size() > offers.size())
				offerListSize = offers.size();
			else
				offerListSize = offerImages.size();
		}

		// Parse relevant information from source site
		for (int i = 0; i < offerListSize; i++) {
			Element offer = offers.get(i);
			Element dataUrl = offerImages.get(i);
			Element price = offerPrice.get(i);
			Element cell = offerCells.get(i);

			String imgUrl = dataUrl.attr("data-original");
			String offerText = offer.text();
			String offerCell = cell.attr("href");

			offerText = offerText.substring(0, offerText.indexOf("(details)"));

			/*
			 * Since some offer-prices don't have the exact same attributes
			 * we have to grab the current price String, and if there are 
			 * no was-price element, we need to specify and mark the offer.
			 */
			if (price != null) {
				String currentPrice = price.attr("current-price");
				String wasPrice = price.attr("was-price");
				if (currentPrice != null) {
					if (wasPrice != null) {
						offerPrices.add(currentPrice);
						offerOldPrices.add(wasPrice);
					}
				}
			}
			offerTitles.add(offerText);
			imgUrls.add(imgUrl);
			offerCellList.add(offerCell);
		}

		// Add the lists to the result list
		returnList.add(offerTitles); returnList.add(imgUrls); returnList.add(offerCellList);

		return returnList;
	}

	public ArrayList<information> search(String keyword, double lat, double lng, int radius) {
		ArrayList<information> resultList = new ArrayList<information>();
		try {
			StringBuilder myBuilder = readUrl(keyword, lat, lng, radius);
			AsyncTask<StringBuilder, Void, StringBuilder> mySyncTask = new JSONParser().execute(myBuilder);
			StringBuilder newBuilder = null;
			JSONArray predsJsonArray = null;

			newBuilder = mySyncTask.get();
			predsJsonArray = convertToJson(newBuilder.toString());

			resultList = convertToInformation(predsJsonArray);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultList;
	}

	public StringBuilder readUrl(String keyword, double lat, double lng, int radius) {

		StringBuilder sb = new StringBuilder(DEALS_API_BASE);
		sb.append("message_status=" + STATUS);
		sb.append("&api_key_token=" + API_KEY_TOKEN);
		sb.append("&api_secret_token=" + API_SECRET_TOKEN);

		sb.append("&lng=" + String.valueOf(lng));
		sb.append("&lat=" + String.valueOf(lat));
		sb.append("&distance=" + String.valueOf(radius));

		return sb;
	}

	public JSONArray convertToJson(String jsonResults) throws Exception{
		// Create a JSON object hierarchy from the results
		JSONObject jsonObj = new JSONObject(jsonResults.toString());
		JSONArray predsJsonArray = jsonObj.getJSONArray("results");
		return predsJsonArray;

	}

	public ArrayList<information> convertToInformation(JSONArray predsJsonArray) throws Exception{
		ArrayList<information> resultList = new ArrayList<information>();


		return resultList;
	}

}

